const jwt = require("jsonwebtoken");
const { dbName, http } = require("../modal/db.config");
const SECRET = dbName;
const { getCurrentDateTime } = require("../modal/time.config");
const STATE = {
  LOW: 0,
  UP: 1,
};
exports.create = async (req, res) => {
  const body = req.body;
  const { title, content, state = STATE.UP } = body;
  const data = {
    title,
    content,
    state,
    createTime: getCurrentDateTime(),
    updateTime: getCurrentDateTime(),
  };
  const result = await req.services.NoticeService.create(data);
  if (result.affectedRows === 1) {
    res.status(200).json({ data: "新增成功", msg: "success", code: 200 });
  } else {
    res.status(200).json({ data: "系统错误，请重试", msg: "fail", code: 500 });
  }
};
exports.update = async (req, res) => {
  const body = req.body;
  const { title, content, state, id } = body;
  const updateTime = getCurrentDateTime();
  console.log();
  const data = {
    title,
    content,
    state,
    updateTime,
  };
  const newData = await req.services.NoticeService.update(data, { id });
  if (newData.affectedRows === 1) {
    res.status(200).json({ data: "更新成功", msg: "success", code: 200 });
  } else {
    res.status(200).json({ data: "系统错误，请重试", msg: "fail", code: 500 });
  }
};

exports.updateState = async (req, res) => {
  const body = req.body;
  const { state, id } = body;
  const updateTime = getCurrentDateTime();
  const data = {
    state,
    updateTime,
  };
  const newData = await req.services.NoticeService.update(data, { id });
  if (newData.affectedRows === 1) {
    res.status(200).json({ data: "更新成功", msg: "success", code: 200 });
  } else {
    res.status(200).json({ data: "系统错误，请重试", msg: "fail", code: 500 });
  }
};

exports.getDetail = async (req, res) => {
  const body = req.query;
  const { id } = body;
  console.log("===", id);
  const newData = await req.services.NoticeService.findById(id);
  if (newData) {
    res.status(200).json({ data: newData, msg: "success", code: 200 });
  } else {
    res.status(200).json({ data: "查无数据", msg: "fail", code: 400 });
  }
};
exports.list = async (req, res) => {
  const body = req.body;
  const { title = "", state = "", page = null, pageSize = null } = body;
  let newData = await req.services.NoticeService.getList({
    pageSize: pageSize,
    page: page,
    where: { state },
    like: { title },
  });
  let count = await req.services.NoticeService.getCount({
    where: { state },
    like: { title },
  });

  res.status(200).json({
    data: {
      list: newData,
      total: count,
    },
    msg: "success",
    code: 200,
  });
};

exports.del = async (req, res) => {
  const body = req.query;
  const { id } = body;
  const newData = await req.services.NoticeService.delete(Number(id));
  if (newData.affectedRows === 1) {
    res.status(200).json({ data: "删除成功", msg: "success", code: 200 });
  } else {
    res.status(200).json({ data: "查无数据", msg: "fail", code: 400 });
  }
};
